package org.kunteng.yunac.util;

import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * Created by Administrator on 2016/1/26.
 */
public class ElasticSearchClient {

    private static ElasticSearchClient client;

    public static ElasticSearchClient getInstance() {
        if (client == null || client.isClosed()) {
            client = new ElasticSearchClient();
        }
        return client;
    }

    private CloseableHttpClient httpClient;
    private boolean closed;

    private boolean isClosed() {
        return closed;
    }

    private ElasticSearchClient() {
        httpClient = HttpClients.createDefault();
        closed = false;
    }

    public Map post(String url, String queryJSON) {

        StringEntity entity = new StringEntity(queryJSON, "utf-8");
        HttpPost post = new HttpPost();
        post.setURI(URI.create(url));
        post.setEntity(entity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
                if (responseStr != null) {
                    return JSONObject.fromObject(responseStr);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    @PreDestroy
    public void close() {
        try {
            if (httpClient != null) {
                httpClient.close();
                closed = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
